package com.neusoft.db;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.neusoft.utils.MyUtil;

public class DBProvider {
	
	/**
	 * 获取SqlSession对象
	 * @return SqlSession对象
	 */
	public SqlSession getSqlSession() {
		SqlSession sqlS = null;
		try {
			//将mybatis配置文件读取到流中
			InputStream isConfigMybatis = DBProvider.class.getClassLoader().getResourceAsStream("config-mybatis.xml");
			//通过properties工具类加载数据库配置文件
			Properties prop = new Properties();
			prop.load(DBProvider.class.getClassLoader().getResourceAsStream("db.properties"));
			//SqlSession的创建类
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//使用builder创建SqlSessionFactory类
			SqlSessionFactory factory = builder.build(isConfigMybatis,prop);
			//获取sqlSession对象
			sqlS = factory.openSession();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sqlS;
	}
	
	
	
	/**
	 * 获取Mapper的实例对象
	 * @param clazz
	 * @return Mapper的实例对象
	 */
	public <T> T getMyMapper(Class<T> clazz) {
		T re_t = null;
		try {
			//将mybatis配置文件读取到流中
			InputStream isConfigMybatis = DBProvider.class.getClassLoader().getResourceAsStream("config-mybatis.xml");
			//通过properties工具类加载数据库配置文件
			Properties prop = new Properties();
			prop.load(DBProvider.class.getClassLoader().getResourceAsStream("db.properties"));
			//SqlSession的创建类
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			//使用builder创建SqlSessionFactory类
			SqlSessionFactory factory = builder.build(isConfigMybatis,prop);
			//获取sqlSession对象
			SqlSession sqlS = factory.openSession(true);
			re_t = sqlS.getMapper(clazz);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return re_t;
	}
}
